


// 常用权限映射，小程序、Android、ios权限名
const permissionMapping = {
	location: {
		permissionName: "定位",
		mpName: 'userLocation',
		androidName: 'android.permission.ACCESS_FINE_LOCATION',
		iosName: "CLLocationManager",
		checkStatus: manager => manager.authorizationStatus()
	},
	camera: {
		permissionName: "相机",
		mpName: 'camera',
		androidName: 'android.permission.CAMERA',
		iosName: "AVCaptureDevice",
		checkStatus: device => device.authorizationStatusForMediaType('vide')
	},
	album: {
		permissionName: "相册",
		mpName: 'camera',
		androidName: 'android.permission.READ_EXTERNAL_STORAGE',
		iosName: "PHPhotoLibrary",
		checkStatus: library => library.authorizationStatus()
	},
	audio: {
		permissionName: "麦克风",
		mpName: 'record',
		androidName: 'android.permission.RECORD_AUDIO',
		iosName: "AVAudioSession",
		checkStatus: session => session.sharedInstance().recordPermission()
	},
	push: {
		permissionName: "推送",
		androidName: 'android.permission.READ_EXTERNAL_STORAGE',
		iosName: "UIApplication",
		checkStatus: app => app.currentUserNotificationSettings().plusGetAttribute("types")
	},
	contact: {
		permissionName: "通讯录",
		androidName: 'android.permission.READ_CONTACTS',
		iosName: "CNContactStore",
		checkStatus: store => store.authorizationStatusForEntityType(0)
	},
	calendar: {
		permissionName: "日历",
		androidName: 'android.permission.READ_CALENDAR',
		iosName: "EKEventStore",
		checkStatus: store => store.authorizationStatusForEntityType(0)
	}
}

// 封装小程序、iOS和Android的权限判断函数
function checkPermission(permissionID) {
	// #ifdef APP-PLUS
	if (uni.getSystemInfoSync().platform === 'ios') {
		return checkIosPermission(permissionID);
	} else {
		return checkAndroidPermission(permissionID);
	}
	// #endif
	
	// #ifdef MP
	return checkMpPermission(permissionID);
	// #endif
}

// iOS权限检查
function checkIosPermission(permissionID) {
	const permission = permissionMapping[permissionID];
	if (permission) {
		// 根据权限名获取权限封装对象
		var importedObject = plus.ios.import(permission.iosName);
		var status = permission.checkStatus(importedObject);
		// 删除iOS对象的封装函数
		plus.ios.deleteObject(importedObject)
		if (status == 3) {
			return Promise.resolve(true)
		} else {
			return Promise.resolve(false)
		}
	}
	return Promise.reject('申请权限错误：不存在此权限');
}

// Android权限请求
function checkAndroidPermission(permissionID) {
	return new Promise((resolve, reject) => {
		const permission = permissionMapping[permissionID];
		if (!permission || !permission.androidName) {
			reject(new Error("不存在此Android权限"));
			return;
		}
		plus.android.requestPermissions(
			[permission.androidName],
			(resultObj) => {
				if (resultObj.deniedAlways && resultObj.deniedAlways.length > 0) {
					uni.$xl.showModal({
						title: '提示',
						content: '操作权限已被拒绝，请手动前往设置',
						confirmText: "立即设置"
					}).then(res => {
						openAppPermissionSetting();
					}).catch(err => {
						resolve(false);
					});
				} else if (resultObj.deniedPresent && resultObj.deniedPresent.length > 0) {
					resolve(false);
				} else if (resultObj.granted && resultObj.granted.length > 0) {
					resolve(true);
				}
			},
			(error) => {
				reject(false);
				console.log('申请权限错误：', error);
			}
		);
	});
}


let scopeArr = [
	"userInfo",
	"userLocation",
	"userLocationBackground",
	"address",
	"invoiceTitle",
	"invoice",
	"werun",
	"record",
	"writePhotosAlbum",
	"camera",
];

async function checkMpPermission(authType) {
	const permission = permissionMapping[authType];
	if (permission && permission.mpName) {
		authType = permission.mpName;
	}
	
	// 检查授权类型是否合法
	if (!scopeArr.includes(authType)) {
		return Promise.reject("请输入正确的授权类型");
	}
	
	let scope = "scope." + authType;
	try {
		// 检查用户是否已经授权
		let isUserSet = await getSettingSync(scope);
		if (isUserSet) {
			return Promise.resolve(true);
		}
		
		// 请求授权
		let isAuthorize = await authorizeSync(scope);
		if (isAuthorize) {
			return Promise.resolve(true);
		}
		
		// 弹框提示用户手动授权
		let showModalMes = await showModalSync(scope);
		if (showModalMes) {
			console.log(123);
			let openSet = await openSettingSync(scope);
			return Promise.resolve(openSet);
		} else {
			return Promise.resolve(false);
		}
	}catch(err) {
		console.log(err);
		return Promise.reject(err)
	}
}


// 判断用户是否开启该授权
function getSettingSync(scope) {
	return new Promise((resolve, reject) => {
		console.log(scope, '256');
		uni.getSetting({
			success(res) {
				if (!res.authSetting[scope]) {
					resolve(false);
				} else {
					resolve(true);
				}
			},
			fail(err) {
				reject(err);
				console.error("uni.getSetting Error", err);
			}
		});
	});
}

// 请求用户授权
function authorizeSync(scope) {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: scope,
			success() {
				resolve(true);
			},
			fail() {
				resolve(false);
			}
		});
	});
}

// 弹框提示用户手动授权
function showModalSync(scope) {
	return new Promise((resolve, reject) => {
		uni.$xl.showModal({
			title: "提示",
			content: `为了更好的用户体验，请您授权 ${scope} 功能`,
			confirmText: "去授权",
			showCancel: false
		}).then(res => {
			resolve(true); // 直接返回用户点击确认的结果
		}).catch(err => {
			resolve(false); // 直接返回用户点击确认的结果
		})
	});
}

// 调起客户端小程序设置界面
function openSettingSync(scope) {
	return new Promise((resolve, reject) => {
		console.log('4959');
		uni.openSetting({
			success(res) {
				console.log(res);
				resolve(res.authSetting[scope]);
			},
			fail(err) {
				console.error("openSettingSync Error", err);
				reject(err);
			}
		});
	})
}


// 打开到app权限设置页面
function openAppPermissionSetting() {
	if (!uni.getSystemInfoSync().platform == 'android') {
		var UIApplication = plus.ios.import("UIApplication");
		var application2 = UIApplication.sharedApplication();
		var NSURL2 = plus.ios.import("NSURL");
		// var setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");		
		var setting2 = NSURL2.URLWithString("app-settings:");
		application2.openURL(setting2);

		plus.ios.deleteObject(setting2);
		plus.ios.deleteObject(NSURL2);
		plus.ios.deleteObject(application2);
	} else {
		// console.log(plus.device.vendor);
		var Intent = plus.android.importClass("android.content.Intent");
		var Settings = plus.android.importClass("android.provider.Settings");
		var Uri = plus.android.importClass("android.net.Uri");
		var mainActivity = plus.android.runtimeMainActivity();
		var intent = new Intent();
		intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
		var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
		intent.setData(uri);
		mainActivity.startActivity(intent);
	}
}

// 检查系统的设备服务是否开启
function checkEnableLocation() {
	if (uni.getSystemInfoSync().platform === 'ios') {
		var result = false;
		var cllocationManger = plus.ios.import("CLLocationManager");
		var result = cllocationManger.locationServicesEnabled();
		console.log("系统定位开启:" + result);
		plus.ios.deleteObject(cllocationManger);
		return result;
	} else {
		var context = plus.android.importClass("android.content.Context");
		var locationManager = plus.android.importClass("android.location.LocationManager");
		var main = plus.android.runtimeMainActivity();
		var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
		var result = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
		console.log("系统定位开启:" + result);
		return result
	}
}
// 打开系统定位设置
function openLocationSetting() {
	if(uni.getSystemInfoSync().platform === 'ios') {
		var cllocationManger = plus.ios.import("CLLocationManager");
		var enable = cllocationManger.locationServicesEnabled();
		var status = cllocationManger.authorizationStatus();
		plus.ios.deleteObject(cllocationManger);
		console.log("手机系统的定位没有打开");
		uni.$xl.showModal({
		    title: '提示',
		    content: '检测到您尚未打开定位服务功能,是否前往开启'
		}).then(res => {
			var UIApplication = plus.ios.import("UIApplication");
			var application2 = UIApplication.sharedApplication();
			var NSURL2 = plus.ios.import("NSURL");
			var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION");
			application2.openURL(setting2);
			plus.ios.deleteObject(setting2);
			plus.ios.deleteObject(NSURL2);
			plus.ios.deleteObject(application2);
		});
	} else {
		uni.$xl.showModal({
		    title: '提示',
		    content: '检测到您尚未打开定位服务功能,是否前往开启'
		}).then(res => {
			var context = plus.android.importClass("android.content.Context");
			var locationManager = plus.android.importClass("android.location.LocationManager");
			var main = plus.android.runtimeMainActivity();
			var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
			if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
			    var main = plus.android.runtimeMainActivity();
				var Intent = plus.android.importClass('android.content.Intent');
				var Settings = plus.android.importClass('android.provider.Settings');
				var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
				main.startActivity(intent); // 打开系统设置GPS服务页面
			}
		})
	}
}

export default {
	checkPermission,  				// 封装小程序、iOS和Android的权限判断函数
	openAppPermissionSetting,   	// 打开app权限设置页面
	
	checkEnableLocation,			// 检查系统的设备定位服务是否开启
	openLocationSetting				// 打开系统定位设置
}